package com.bjtime.designer

import android.content.Context
import android.content.pm.ApplicationInfo
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.os.Build
import android.support.annotation.Nullable
import android.text.TextUtils
import android.view.View
import android.view.ViewTreeObserver.OnGlobalLayoutListener
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.IOException


class utils {

    interface  ShotCallback {
        fun OnShoted (b:Bitmap?) {

        }
    }


    companion object {


        fun Bitmap2ByteArray (b : Bitmap) : ByteArray {
            var oust = ByteArrayOutputStream ()
            b.compress(Bitmap.CompressFormat.JPEG, 100, oust)
            oust.flush()
            oust.close()
            return oust.toByteArray()
        }

        fun writeFile (s : String, b : ByteArray) {
            val file = File(s)
            file.writeBytes(b)
        }

        fun isDebugApp(context: Context): Boolean {
            try {
                val info = context.applicationInfo
                return info.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0
            } catch (x: Exception) {
                return false
            }

        }


        fun px2sp (context : Context, pxValue: Float): Int {
            val scale = context.resources.displayMetrics.density
            return (pxValue / scale + 0.5f).toInt()
        }
        /**
         * DP转像素
         */
        fun sp2px (context : Context, dpValue: Float): Int {
            val scale = context.resources.displayMetrics.density
            return (dpValue * scale + 0.5f).toInt()
        }

        /**
         * DP转像素
         */
        fun dp2px (context : Context, dpValue: Float): Int {
            val scale = context.resources.displayMetrics.density
            return (dpValue * scale + 0.5f).toInt()
        }

        /**
         * 像素转毫米
         */
        fun px2mm (context : Context, dpValue: Float): Int {
            val scale = context.resources.displayMetrics.density
            return (dpValue * scale + 0.5f).toInt()
        }

        /**
         * 毫米转像素
         */
        fun mm2Px (context : Context, mmValue : Float) : Float {
            val scale = context.resources.displayMetrics
            return (mmValue * scale.xdpi * (1.0f / 25.4f)).toFloat()
        }


        /**
         * view截图
         * @return
         */
        fun viewShot (v: View) : Bitmap? {
            if (null == v) {
                return null
            }
            val bitmap = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888)
            val c = Canvas(bitmap)
            v.draw(c)
            return bitmap
        }

    }





}